import { defineStore } from 'pinia'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import Layout from '@/layout/index.vue'
import { RouteRecordRaw } from 'vue-router'
import { ref } from 'vue'
import { cloneDeep } from 'lodash-es'
import { RouterVO } from '@/api/permission/type'

const modules = import.meta.glob(`@/views/**/*.vue`)

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref<RouteRecordRaw[]>([])
  const addRoutes = ref<RouteRecordRaw[]>([])
  const defaultRoutes = ref<RouteRecordRaw[]>([])
  const sidebarRouters = ref<RouteRecordRaw[]>([])

  const getRoutes = (): RouteRecordRaw[] => {
    return routes.value as RouteRecordRaw[]
  }
  const getDefaultRoutes = (): RouteRecordRaw[] => {
    return defaultRoutes.value as RouteRecordRaw[]
  }
  const getSidebarRoutes = (): RouteRecordRaw[] => {
    return sidebarRouters.value as RouteRecordRaw[]
  }

  const setRoutes = (newRoutes: RouteRecordRaw[]): void => {
    addRoutes.value = newRoutes
    routes.value = constantRoutes.concat(newRoutes)
  }
  const setDefaultRoutes = (routes: RouteRecordRaw[]): void => {
    defaultRoutes.value = constantRoutes.concat(routes)
  }
  const setSidebarRouters = (routes: RouteRecordRaw[]): void => {
    sidebarRouters.value = routes
  }

  const generateRoutes = (routes: RouterVO[]) => {
    const splitRoutes = filterAsyncRouter(routes)
    setRoutes(cloneDeep(splitRoutes))
    setSidebarRouters(constantRoutes.concat(splitRoutes))
    setDefaultRoutes(cloneDeep(splitRoutes))
    return splitRoutes
  }

  /**
   * 遍历后台传来的路由字符串，转换为组件对象
   * @param asyncRouterMap 后台传来的路由字符串
   * @param lastRouter 上一级路由
   */
  const filterAsyncRouter = (menuList: RouterVO[]): RouteRecordRaw[] => {
    const asyncRouters: RouteRecordRaw[] = []
    menuList.forEach((item) => {
      const route: RouteRecordRaw = {
        name: item.name,
        path: item.path,
        component:
          item.component === 'Layout' ? Layout : modules[`/src/views/${item.component}.vue`],
        children: [],
        meta: {
          title: item.meta.title,
          icon: item.meta.icon,
          noCache: item.meta.noCache,
          link: item.meta.link,
          single: item.meta.single
        }
      }
      if (item.children != null && item.children && item.children.length) {
        route.children = filterAsyncRouter(item.children)
      } else {
        delete route.children
        delete route.redirect
      }
      asyncRouters.push(route)
    })
    return asyncRouters
  }

  return {
    routes,
    sidebarRouters,
    defaultRoutes,

    getRoutes,
    getDefaultRoutes,
    getSidebarRoutes,

    setRoutes,
    setDefaultRoutes,
    setSidebarRouters,

    generateRoutes
  }
})
